package shuiyuqing.network.http;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import com.alibaba.fastjson.JSON;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.xkh.xkh.R;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import managers.DatabaseManager;
import com.xkh.xkh.MyApplication;
import managers.VolleySingleton;
import shuiyuqing.network.beans.IrrBAWaterGate;
import shuiyuqing.network.beans.IrrBRStadia;
import shuiyuqing.network.beans.IrrBTCanalDetail;

/**
 * 获取渠道、闸门、测站的基本信息
 * Created by 凯 on 2015/11/5.
 */
public class GetBasicInfo {


    // 下行数据
    Download download;

    // 设置回调
    Runnable runnable;


    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    // 获取基本的信息
    public void get() {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/guanqu/GetBasicInfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        afterGet(response);
                        afterall();
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                afterall();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }

    private void afterall() {
        if (runnable != null) {
            runnable.run();
        }
    }

    // 获取下载信息后
    private void afterGet(String response) {
        download = JSON.parseObject(response, Download.class);
        if (download.getStatus() == DownloadInfo.SUCCESS) {
            // 保存信息
            save(download);
        } else if (download.getStatus() == DownloadInfo.FAILED) {

        }
    }

    // 保存基本信息
    private void save(Download download) {

        SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
        db.beginTransaction();

        try {

            for (IrrBAWaterGate gate : download.getIrrBAWaterGates()) {
                ContentValues cv = new ContentValues();

                cv.put("watergateCode", gate.getWatergateCode());
                cv.put("canalCode", gate.getCanalCode());
                cv.put("watergateName", gate.getWatergateName());
                cv.put("watergateType", gate.getWatergateType());
                cv.put("watergateMET", gate.getWatergateMET());
                cv.put("watergateLC", gate.getWatergateLC());
                cv.put("watergateNUM", gate.getWatergateNUM() + "");
                cv.put("watergateHeight", gate.getWatergateHeight() + "");
                cv.put("watergateWtdth", gate.getWatergateWtdth() + "");
                cv.put("watergateQ", gate.getWatergateQ() + "");
                cv.put("watergateMTP", gate.getWatergateMTP() + "");
                cv.put("watergateStatus", gate.getWatergateStatus() + "");
                cv.put("orderNum",gate.getOrderNum());
//                cv.put("stadiaCode",gate.getStadiaCode());
                String stdiaCode = getGateStdiaCode(gate, download.getIrrBRStadias());
                cv.put("stadiaCode", stdiaCode);
                cv.put("designWaterLevel", gate.getDesignWaterLevel() + "");

                cv.put("engManCd", gate.getEngManCd());
                cv.put("gaocheng",gate.getFloorElevation()+"");
                cv.put("telephone", gate.getTelephone());
                if (gate.getTimeSign() != null)
                    cv.put("timeSign", gate.getTimeSign().getTimeInMillis());
                cv.put("remark", gate.getRemark());

                db.insert("t_IrrBAWaterGate", null, cv);
            }

            for (IrrBTCanalDetail canalDetail : download.getIrrBTCanalDetails()) {
                ContentValues cv = new ContentValues();
                cv.put("canalCode", canalDetail.getCanalCode());
                cv.put("canalName", canalDetail.getCanalName());
                cv.put("canalG", canalDetail.getCanalG() + "");
                cv.put("canalDesQ", canalDetail.getCanalDesQ() + "");
                cv.put("leakR", canalDetail.getLeakR() + "");
                cv.put("canalLen", canalDetail.getCanalLen() + "");
                cv.put("lineLen", canalDetail.getLineLen() + "");
                cv.put("engManCd", canalDetail.getEngManCd());
                cv.put("uperCanalCd", canalDetail.getUperCanalCd());
                if (canalDetail.getTimeSign() != null)
                    cv.put("timeSign", canalDetail.getTimeSign().getTimeInMillis());
                cv.put("remark", canalDetail.getRemark());
                cv.put("stadiaCode", canalDetail.getStadiaCode());

                db.insert("t_IrrBTCanalDetail", null, cv);
            }


            for (IrrBRStadia stadia : download.getIrrBRStadias()) {
                ContentValues cv = new ContentValues();
                cv.put("stadiaCode", stadia.getStadiaCode());
                cv.put("stadiaName", stadia.getStadiaName());
                cv.put("stadiaType", stadia.getStadiaType());
                cv.put("locCode", stadia.getLocCode());
                cv.put("stbk", stadia.getStbk() + "");
                cv.put("flowDir", stadia.getFlowDir() + "");
                cv.put("datTp", stadia.getDatTp());
                cv.put("datElev", stadia.getDatElev() + "");
                cv.put("modBasVal", stadia.getModBasVal() + "");
                cv.put("modPara", stadia.getModPara() + "");
                if (stadia.getEstStYm() != null)
                    cv.put("estStYm", stadia.getEstStYm().getTimeInMillis());
                cv.put("runCond", stadia.getRunCond() + "");
                cv.put("engManCd", stadia.getEngManCd());
                if (stadia.getTimeSign() != null)
                    cv.put("timeSign", stadia.getTimeSign().getTimeInMillis());
                cv.put("remark", stadia.getRemark());
                cv.put("elevation",stadia.getElevation()+"");
                System.out.println(stadia.getElevation());
                db.insert("t_IrrBRStadia", null, cv);
            }

            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
            DatabaseManager.getInstance().closeDatabase();
        }
    }

    private String getGateStdiaCode(IrrBAWaterGate gate, List<IrrBRStadia> irrBRStadias) {
        for (IrrBRStadia stadia : irrBRStadias) {
            if (gate.getWatergateCode().equals(stadia.getLocCode())) {
                return stadia.getStadiaCode();
            }
        }
        return null;
    }


    // 下行数据
    public static class Download {
        int status;
        // 渠道基本信息
        List<IrrBTCanalDetail> irrBTCanalDetails = new ArrayList<IrrBTCanalDetail>();

        // 测站信息
        List<IrrBRStadia> irrBRStadias = new ArrayList<IrrBRStadia>();

        // 水闸信息
        List<IrrBAWaterGate> irrBAWaterGates = new ArrayList<IrrBAWaterGate>();

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<IrrBTCanalDetail> getIrrBTCanalDetails() {
            return irrBTCanalDetails;
        }

        public void setIrrBTCanalDetails(List<IrrBTCanalDetail> irrBTCanalDetails) {
            this.irrBTCanalDetails = irrBTCanalDetails;
        }

        public List<IrrBRStadia> getIrrBRStadias() {
            return irrBRStadias;
        }

        public void setIrrBRStadias(List<IrrBRStadia> irrBRStadias) {
            this.irrBRStadias = irrBRStadias;
        }

        public List<IrrBAWaterGate> getIrrBAWaterGates() {
            return irrBAWaterGates;
        }

        public void setIrrBAWaterGates(List<IrrBAWaterGate> irrBAWaterGates) {
            this.irrBAWaterGates = irrBAWaterGates;
        }


    }
}
